﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace Inventory.Test.Library.Rules
{
    [DisplayName("Extract Grid Views")]
    [Description("Extract any GridView found in the Http Response")]
    public class ExtractGridViews : ExtractionRule
    {
        public const string GRID_PREFIX = "$GRID.";



        /// <summary>
        /// Extract ID of grid view from the provided string
        /// </summary>
        /// <param name="tableOpeningTag">For example:&lt;table class="gridview" cellspacing="0" rules="all" PageButtonCount="10" border="1" id="ctl00_ContentPlaceHolder1_GridView1"&gt; </param>
        /// <returns></returns>
        static string  GetEntityID(string tableOpeningTag)
        {
            if (string.IsNullOrEmpty(tableOpeningTag))
                throw new NullReferenceException("Cannont extract grid view id from empty string");

            string idPrefix = "id=\"";
            int startIndex = tableOpeningTag.IndexOf(idPrefix) + idPrefix.Length;
            int endIndex = tableOpeningTag.IndexOf('"', startIndex);
            int charctersLength = endIndex - startIndex;

            string entityID = tableOpeningTag.Substring(startIndex, charctersLength);
            return entityID;//.Replace("_", "$");

        }

        public static List<string> Extract(string bodyString)
        {
            string pattern = "<table.*PageButtonCount[^>]*>";

            Regex _FindAnchorTags = new Regex(
            pattern,
            RegexOptions.IgnoreCase
            | RegexOptions.Multiline
            | RegexOptions.IgnorePatternWhitespace
            | RegexOptions.Compiled
            );


            var extractMatches = _FindAnchorTags.Matches(bodyString);

            List<string> gridsIDList = new List<string>();

            for (int i = 0; i < extractMatches.Count; i++)
            {
                Match extractMatch = extractMatches[i];

                string shortKey = GRID_PREFIX + i;
                string gridID = GetEntityID(extractMatch.Value);
                gridsIDList.Add(gridID);                
            }
            return gridsIDList;
        }
        public override void Extract(object sender, ExtractionEventArgs e)
        {
            string body = e.Response.BodyString;
            List<string> gridIDList = Extract(body);

            for (int i = 0; i < gridIDList.Count; i++)
            {
                string gridID = gridIDList[i];

                string shortKey = GRID_PREFIX + i;
                e.WebTest.Context[shortKey] = gridID;

                e.Success = true;
            }

            if (e.Success)
                e.Message = "grid view extracted.";
            else
                e.Message = "No grid view extracted.";
        }
    }
}
